package com.nihome.entershopinfo.fragments;

import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nihome.entershopinfo.Constants;
import com.nihome.entershopinfo.R;
import com.nihome.entershopinfo.application.SysApplication;
import com.nihome.entershopinfo.dialog.LoadingDialog;
import com.nihome.entershopinfo.entity.User;
import com.nihome.entershopinfo.entity.request.SendInfoReq;
import com.nihome.entershopinfo.entity.response.ExpandsLogRes;
import com.nihome.entershopinfo.entity.response.ResponseBase;
import com.nihome.entershopinfo.ui.HomePageActivity;
import com.nihome.entershopinfo.utils.Log;
import com.nihome.entershopinfo.utils.NetUtil;
import com.nihome.entershopinfo.utils.RequestAPI;
import com.nihome.entershopinfo.utils.StringUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Response;

/**
 * Created by Carson on 2017/7/19.
 */
public class SendInfoFragment extends Fragment implements LocationSource, AMapLocationListener, View.OnClickListener{
    private static final String TAG = "SendInfoFragment";
    private Context mContext;
    private NetUtil mNetUtil;
    private Gson mGson;
    private User mUser;
    private LoadingDialog loadingDialog;

    private int selectType;
    private ExpandsLogRes expandsLog;

    private SendInfoReq sendInfoReq;
    private String auditId;
    private short operation;

    private TextView basicInfoPrompt;
    private Spinner sendWaySpinner;
    private Spinner whetherSendTypeSpinner;
    private LinearLayout chargingTypeLayout;
    private Spinner chargingTypeSpinner;
    private LinearLayout fixedSendFreeLayout;
    private EditText fixedSendFreeEdit;

    private EditText sendMemo;
    private EditText addressView;
    private TextView locationBtn;
    private EditText takeOutDeliverFeeEdit;
    private EditText packFeeEdit;
    private LinearLayout daDaInfoLayout;
    private EditText registerSendPhone;
    private EditText registerSendContacts;
    private EditText registerSendEmail;
    private EditText registerCardNo;
    private LinearLayout sendLayout;
    private EditText sendFreeEdit;
    private EditText sendMaxDistanceEdit;
    private EditText sendFirstTimeEdit;

    private TextView sendInfoBack;
    private TextView goNextBtn;



    private AMap aMap;
    private MapView mMapView;
    //声明AMapLocationClient类对象，定位发起端
    private AMapLocationClient mLocationClient = null;
    //声明mLocationOption对象，定位参数
    public AMapLocationClientOption mLocationOption = null;
    //声明mListener对象，定位监听器
    private OnLocationChangedListener mListener = null;
    //标识，用于判断是否只显示一次定位信息和用户重新定位
    private boolean isFirstLoc = true;
    private String longitude;
    private String latitude;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        mGson = new Gson();
        mNetUtil = new NetUtil(mContext);
        mUser = SysApplication.getInstance().getmUser();
        loadingDialog = new LoadingDialog(mContext);
        selectType = getArguments().getInt(Constants.SELECT_TYPE);
        expandsLog = getArguments().getParcelable(Constants.DATA);
        auditId = SysApplication.getInstance().getAuditId();
        if (expandsLog.getTakeOutInfoResponseDTO() == null) operation = Constants.NEW;
        else operation = Constants.UPDATE;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_send_info, container, false);
        /** 初始化高德地图 */
        initMap(view, savedInstanceState);

        basicInfoPrompt = (TextView) view.findViewById(R.id.basic_info_prompt);
        sendWaySpinner = (Spinner) view.findViewById(R.id.send_type_spinner);
        whetherSendTypeSpinner = (Spinner) view.findViewById(R.id.whether_send_type);
        chargingTypeLayout = (LinearLayout) view.findViewById(R.id.charging_type_layout);
        chargingTypeSpinner = (Spinner) view.findViewById(R.id.charging_type_spinner);
        fixedSendFreeLayout = (LinearLayout) view.findViewById(R.id.fixed_send_free_layout);
        fixedSendFreeEdit = (EditText) view.findViewById(R.id.fixed_send_free_edit);


        sendMemo = (EditText) view.findViewById(R.id.send_memo);
        addressView = (EditText) view.findViewById(R.id.address_view);
        locationBtn = (TextView) view.findViewById(R.id.location_btn);
        takeOutDeliverFeeEdit = (EditText) view.findViewById(R.id.takeOut_deliver_fee_edit);
        packFeeEdit = (EditText) view.findViewById(R.id.pack_fee_edit);
        daDaInfoLayout = (LinearLayout) view.findViewById(R.id.da_da_info_layout);
        registerSendPhone = (EditText) view.findViewById(R.id.register_send_phone);
        registerSendContacts = (EditText) view.findViewById(R.id.register_send_contacts);
        registerSendEmail = (EditText) view.findViewById(R.id.register_send_email);
        registerCardNo = (EditText) view.findViewById(R.id.register_card_no);
        sendLayout = (LinearLayout) view.findViewById(R.id.send_layout);
        sendFreeEdit = (EditText) view.findViewById(R.id.send_free_edit);
        sendMaxDistanceEdit = (EditText) view.findViewById(R.id.send_max_distance_edit);
        sendFirstTimeEdit = (EditText) view.findViewById(R.id.send_first_time_edit);
        sendInfoBack = (TextView) view.findViewById(R.id.send_info_go_back);
        goNextBtn = (TextView) view.findViewById(R.id.send_info_go_next);

        sendWaySpinner.setOnItemSelectedListener(new SendWaySpinnerListener());
        whetherSendTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 1) {
                    sendLayout.setVisibility(View.VISIBLE);
                    daDaInfoLayout.setVisibility(View.VISIBLE);
                    chargingTypeLayout.setVisibility(View.VISIBLE);
                    if (chargingTypeSpinner.getSelectedItemPosition() == 0) fixedSendFreeLayout.setVisibility(View.VISIBLE);
                } else {
                    chargingTypeLayout.setVisibility(View.GONE);
                    fixedSendFreeLayout.setVisibility(View.GONE);

                    if (sendWaySpinner.getSelectedItemPosition() == 0) {
                        sendLayout.setVisibility(View.GONE);
                        daDaInfoLayout.setVisibility(View.VISIBLE);
                    } else {
                        sendLayout.setVisibility(View.VISIBLE);
                        daDaInfoLayout.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        chargingTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) fixedSendFreeLayout.setVisibility(View.VISIBLE);
                else fixedSendFreeLayout.setVisibility(View.GONE);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        basicInfoPrompt.setText(Html.fromHtml(getString(R.string.basic_info_prompt)));
        sendInfoBack.setOnClickListener(this);
        goNextBtn.setOnClickListener(this);
        locationBtn.setOnClickListener(this);
        if (operation == Constants.UPDATE) initData();
        return view;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        Log.e(TAG, "hidden======" + hidden);
        super.onHiddenChanged(hidden);
        if (!hidden) {
            selectType = getArguments().getInt(Constants.SELECT_TYPE);
            expandsLog = getArguments().getParcelable(Constants.DATA);
            auditId = SysApplication.getInstance().getAuditId();
            if (expandsLog.getTakeOutInfoResponseDTO() == null) operation = Constants.NEW;
            else operation = Constants.UPDATE;
        }
        if (operation == Constants.NEW) viewInit();
        if (operation == Constants.UPDATE) initData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.location_btn:
                if (!mNetUtil.isNetConnected()) {
                    Toast.makeText(mContext, getString(R.string.cannot_connect_network), Toast.LENGTH_SHORT).show();
                    return;
                }
                isFirstLoc = true;
                location();
                break;
            case R.id.send_info_go_back:
                ((HomePageActivity)getActivity()).backClick();
                break;
            case R.id.send_info_go_next:
                if (!mNetUtil.isNetConnected()) {
                    Toast.makeText(mContext, getString(R.string.cannot_connect_network), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (check()) subSendInfo();
                else Toast.makeText(mContext, getString(R.string.submit_prompt), Toast.LENGTH_SHORT).show();
                //((HomePageActivity)getActivity()).goNextOfSendInfo();
                break;
        }
    }

    private void initData(){
        if (expandsLog.getTakeOutInfoResponseDTO().getDeliverType() == 10) sendWaySpinner.setSelection(1);
        else if (expandsLog.getTakeOutInfoResponseDTO().getDeliverType() == 11) sendWaySpinner.setSelection(0);
        if (!StringUtils.isEmpty(sendMemo.getText().toString())) sendMemo.setText(sendMemo.getText().toString());
        addressView.setText(expandsLog.getTakeOutInfoResponseDTO().getLocation());
        takeOutDeliverFeeEdit.setText(expandsLog.getTakeOutInfoResponseDTO().getTakeOutDeliverFee().toString());
        packFeeEdit.setText(expandsLog.getTakeOutInfoResponseDTO().getPackingFee().toString());
        longitude = expandsLog.getTakeOutInfoResponseDTO().getLongitude();
        latitude = expandsLog.getTakeOutInfoResponseDTO().getLatitude();

        if (expandsLog.getTakeOutInfoResponseDTO().getEnableSwitchDelivery()) {
            sendFreeEdit.setText(expandsLog.getTakeOutInfoResponseDTO().getDeliverFeeFixed().toString());
            sendMaxDistanceEdit.setText(expandsLog.getTakeOutInfoResponseDTO().getDeliveryKM().toString());
            sendFirstTimeEdit.setText(expandsLog.getTakeOutInfoResponseDTO().getStartingInterval().toString());
            registerSendPhone.setText(expandsLog.getTakeOutInfoResponseDTO().getDadaMobile());
            registerSendContacts.setText(expandsLog.getTakeOutInfoResponseDTO().getDadaContactsName());
            registerSendEmail.setText(expandsLog.getTakeOutInfoResponseDTO().getDadaEmail());
            registerCardNo.setText(expandsLog.getTakeOutInfoResponseDTO().getContactsIdentifyCard());


            whetherSendTypeSpinner.setSelection(1);
            chargingTypeLayout.setVisibility(View.VISIBLE);
            if (expandsLog.getTakeOutInfoResponseDTO().getSwitchDeliverFeeType() != null &&
                    expandsLog.getTakeOutInfoResponseDTO().getSwitchDeliverFeeType() == 9) {
                chargingTypeSpinner.setSelection(0);
                fixedSendFreeLayout.setVisibility(View.VISIBLE);
                fixedSendFreeEdit.setText(expandsLog.getTakeOutInfoResponseDTO().getSwitchableDeliverFeeFixed().toString());
            }
            if (expandsLog.getTakeOutInfoResponseDTO().getSwitchDeliverFeeType() != null &&
                    expandsLog.getTakeOutInfoResponseDTO().getSwitchDeliverFeeType() == 10) {
                chargingTypeSpinner.setSelection(1);
            }
            if (expandsLog.getTakeOutInfoResponseDTO().getSwitchDeliverFeeType() != null &&
                    expandsLog.getTakeOutInfoResponseDTO().getSwitchDeliverFeeType() == 11) {
                chargingTypeSpinner.setSelection(2);
            }
        } else {
            if (expandsLog.getTakeOutInfoResponseDTO().getDeliverType() == 10) {
                sendFreeEdit.setText(expandsLog.getTakeOutInfoResponseDTO().getDeliverFeeFixed().toString());
                sendMaxDistanceEdit.setText(expandsLog.getTakeOutInfoResponseDTO().getDeliveryKM().toString());
                sendFirstTimeEdit.setText(expandsLog.getTakeOutInfoResponseDTO().getStartingInterval().toString());
            }
            if (expandsLog.getTakeOutInfoResponseDTO().getDeliverType() == 11) {
                registerSendPhone.setText(expandsLog.getTakeOutInfoResponseDTO().getDadaMobile());
                registerSendContacts.setText(expandsLog.getTakeOutInfoResponseDTO().getDadaContactsName());
                registerSendEmail.setText(expandsLog.getTakeOutInfoResponseDTO().getDadaEmail());
                registerCardNo.setText(expandsLog.getTakeOutInfoResponseDTO().getContactsIdentifyCard());
            }

            whetherSendTypeSpinner.setSelection(0);
            chargingTypeLayout.setVisibility(View.GONE);
            fixedSendFreeLayout.setVisibility(View.GONE);
        }


    }

    void viewInit(){
        whetherSendTypeSpinner.setSelection(0);

        sendWaySpinner.setSelection(0);
        sendMemo.setText("");
        isFirstLoc = true;
        location();
        longitude = "";
        latitude = "";
        takeOutDeliverFeeEdit.setText("");
        packFeeEdit.setText("");
        sendFreeEdit.setText("");
        sendMaxDistanceEdit.setText("");
        sendFirstTimeEdit.setText("");
        registerSendPhone.setText("");
        registerSendContacts.setText("");
        registerSendEmail.setText("");
        registerCardNo.setText("");
        chargingTypeLayout.setVisibility(View.GONE);
        chargingTypeSpinner.setSelection(0);
        fixedSendFreeLayout.setVisibility(View.GONE);
        fixedSendFreeEdit.setText("");

    }

    private Boolean check(){
        if (StringUtils.isEmpty(addressView.getText().toString())) return false;
        if (StringUtils.isEmpty(takeOutDeliverFeeEdit.getText().toString())) return false;
        if (StringUtils.isEmpty(packFeeEdit.getText().toString())) return false;
        if (whetherSendTypeSpinner.getSelectedItemPosition() == 0) {
            if (sendWaySpinner.getSelectedItemPosition() == 0) {
                if (StringUtils.isEmpty(registerSendPhone.getText().toString())) return false;
                if (StringUtils.isEmpty(registerSendContacts.getText().toString())) return false;
                if (StringUtils.isEmpty(registerSendEmail.getText().toString())) return false;
                if (StringUtils.isEmpty(registerCardNo.getText().toString())) return false;
            }
            if (sendWaySpinner.getSelectedItemPosition() == 1) {
                if (StringUtils.isEmpty(sendFreeEdit.getText().toString())) return false;
                if (StringUtils.isEmpty(sendMaxDistanceEdit.getText().toString())) return false;
                if (StringUtils.isEmpty(sendFirstTimeEdit.getText().toString())) return false;
            }
        } else {
            if (StringUtils.isEmpty(registerSendPhone.getText().toString())) return false;
            if (StringUtils.isEmpty(registerSendContacts.getText().toString())) return false;
            if (StringUtils.isEmpty(registerSendEmail.getText().toString())) return false;
            if (StringUtils.isEmpty(registerCardNo.getText().toString())) return false;
            if (StringUtils.isEmpty(sendFreeEdit.getText().toString())) return false;
            if (StringUtils.isEmpty(sendMaxDistanceEdit.getText().toString())) return false;
            if (StringUtils.isEmpty(sendFirstTimeEdit.getText().toString())) return false;
        }

        if (whetherSendTypeSpinner.getSelectedItemPosition() == 1 && chargingTypeSpinner.getSelectedItemPosition() == 0) {
            if (StringUtils.isEmpty(fixedSendFreeEdit.getText().toString())) return false;
        }
        return true;
    }

    private void subSendInfo(){
        loadingDialog.show(getString(R.string.load_text));
        sendInfoReq = new SendInfoReq();
        sendInfoReq.setAuditId(auditId);
        sendInfoReq.setMarketerId(mUser.getUserId());
        sendInfoReq.setDeliverType(sendWaySpinner.getSelectedItemPosition() == 0 ? (short) 11 : (short) 10);
        if (!StringUtils.isEmpty(sendMemo.getText().toString())) sendInfoReq.setTakeOutMemo(sendMemo.getText().toString());
        sendInfoReq.setEnableSwitchDelivery(whetherSendTypeSpinner.getSelectedItemPosition() == 0 ? false : true);
        if (whetherSendTypeSpinner.getSelectedItemPosition() == 1) {
            sendInfoReq.setDadaMobile(registerSendPhone.getText().toString());
            sendInfoReq.setDadaContactsName(registerSendContacts.getText().toString());
            sendInfoReq.setDadaEmail(registerSendEmail.getText().toString());
            sendInfoReq.setContactsIdentifyCard(registerCardNo.getText().toString());
            String deliverFeeFixed = sendFreeEdit.getText().toString();
            sendInfoReq.setDeliverFeeFixed(new BigDecimal(deliverFeeFixed).setScale(2, BigDecimal.ROUND_HALF_UP));
            String maxDistance = sendMaxDistanceEdit.getText().toString();
            sendInfoReq.setDeliveryKM(Double.valueOf(maxDistance));
            int startingInterval = Integer.valueOf(sendFirstTimeEdit.getText().toString());
            sendInfoReq.setStartingInterval(startingInterval);

            if (chargingTypeSpinner.getSelectedItemPosition() == 0) {
                sendInfoReq.setSwitchDeliverFeeType((short)9);
                BigDecimal bigDecimal = new BigDecimal(fixedSendFreeEdit.getText().toString());
                sendInfoReq.setSwitchableDeliverFeeFixed(bigDecimal);
            }
            if (chargingTypeSpinner.getSelectedItemPosition() == 1) sendInfoReq.setSwitchDeliverFeeType((short)10);
            if (chargingTypeSpinner.getSelectedItemPosition() == 2) sendInfoReq.setSwitchDeliverFeeType((short)11);
        } else {
            if (sendWaySpinner.getSelectedItemPosition() == 0) {
                sendInfoReq.setDadaMobile(registerSendPhone.getText().toString());
                sendInfoReq.setDadaContactsName(registerSendContacts.getText().toString());
                sendInfoReq.setDadaEmail(registerSendEmail.getText().toString());
                sendInfoReq.setContactsIdentifyCard(registerCardNo.getText().toString());
            }
            if (sendWaySpinner.getSelectedItemPosition() == 1) {
                String deliverFeeFixed = sendFreeEdit.getText().toString();
                sendInfoReq.setDeliverFeeFixed(new BigDecimal(deliverFeeFixed).setScale(2, BigDecimal.ROUND_HALF_UP));
                String maxDistance = sendMaxDistanceEdit.getText().toString();
                sendInfoReq.setDeliveryKM(Double.valueOf(maxDistance));
                int startingInterval = Integer.valueOf(sendFirstTimeEdit.getText().toString());
                sendInfoReq.setStartingInterval(startingInterval);
            }
        }

        sendInfoReq.setOperation(operation);
        sendInfoReq.setLocation(addressView.getText().toString());
        sendInfoReq.setLongitude(longitude);
        sendInfoReq.setLatitude(latitude);
        String takeOutDeliverFee = takeOutDeliverFeeEdit.getText().toString();
        sendInfoReq.setTakeOutDeliverFee(new BigDecimal(takeOutDeliverFee).setScale(2, BigDecimal.ROUND_HALF_UP));
        String packFee = packFeeEdit.getText().toString();
        sendInfoReq.setPackingFee(new BigDecimal(packFee).setScale(2, BigDecimal.ROUND_HALF_UP));




        Log.e(TAG, "subSendInfo json = " + new Gson().toJson(sendInfoReq));
        OkHttpUtils.postString().url(RequestAPI.SEND_INFO_URL)
                .content(new Gson().toJson(sendInfoReq))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build().execute(new SendInfoCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e(TAG, e + "");
                        loadingDialog.dismiss();
                        if (e instanceof UnknownHostException) {
                            Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (e instanceof SocketException) {
                            Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (e instanceof SocketTimeoutException) {
                            Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (e instanceof IOException) {
                            Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                            return;
                        }

                        Toast.makeText(mContext, getString(R.string.service_error), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(ResponseBase<String> response, int id) {
                        loadingDialog.dismiss();
                        switch (Integer.valueOf(response.getResultCode())) {
                            case Constants.REQ_SUCCESS:
                                expandsLog.setTakeOutInfoResponseDTO(sendInfoReq);
                                ((HomePageActivity)getActivity()).goNextOfSendInfo();
                                break;
                            default:
                                Toast.makeText(mContext, response.getMsg(), Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
        });
    }

    abstract class SendInfoCallback extends Callback<ResponseBase<String>> {
        @Override
        public ResponseBase<String> parseNetworkResponse(Response response, int id) throws Exception {
            String string = response.body().string();
            Log.e(TAG, string);
            Type jsonType = new TypeToken<ResponseBase<String>>(){}.getType();
            ResponseBase<String> res = mGson.fromJson(string, jsonType);
            return res;
        }
    }


    class SendWaySpinnerListener implements AdapterView.OnItemSelectedListener{
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (whetherSendTypeSpinner.getSelectedItemPosition() == 0) {
                if (position == 0) {
                    daDaInfoLayout.setVisibility(View.VISIBLE);
                    sendLayout.setVisibility(View.GONE);
                }
                if (position == 1) {
                    sendLayout.setVisibility(View.VISIBLE);
                    daDaInfoLayout.setVisibility(View.GONE);
                }
            } else {
                sendLayout.setVisibility(View.VISIBLE);
                daDaInfoLayout.setVisibility(View.VISIBLE);
            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    }

























    private void initMap(View view, Bundle savedInstanceState){
        mMapView = (MapView) view.findViewById(R.id.mapView);
        mMapView.onCreate(savedInstanceState);
        aMap = mMapView.getMap();
        UiSettings settings = aMap.getUiSettings();  //设置显示定位按钮 并且可以点击
        aMap.setLocationSource(this);     //设置定位监听
        aMap.setMyLocationEnabled(true);  // 是否可触发定位并显示定位层
        settings.setMyLocationButtonEnabled(false);  // 是否显示定位按钮
        aMap.getUiSettings().setZoomControlsEnabled(false);
        //定位的小图标 默认是蓝点 这里自定义一团火，其实就是一张图片
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        checkPermission();
    }


    private void location() {
        loadingDialog.show("正在定位...");
        //初始化定位
        mLocationClient = new AMapLocationClient(mContext.getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    //激活定位
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
    }

    //停止定位
    @Override
    public void deactivate() {
        mListener = null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                Log.e(TAG, "城市 =" + aMapLocation.getCity());//城市信息
                Log.e(TAG, "城区 =" + aMapLocation.getDistrict());//城区信息
                Log.e(TAG, "街道信息 =" + aMapLocation.getStreet());//街道信息
                Log.e(TAG, "街道门牌号 =" + aMapLocation.getStreetNum());//街道门牌号信息
                //定位成功回调信息，设置相关消息
                aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见官方定位类型表
                latitude = String.valueOf(aMapLocation.getLatitude());//获取纬度
                longitude = String.valueOf(aMapLocation.getLongitude()) ;//获取经度
                aMapLocation.getAccuracy();//获取精度信息
                aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                aMapLocation.getCountry();//国家信息
                aMapLocation.getProvince();//省信息
                aMapLocation.getCity();//城市信息
                aMapLocation.getDistrict();//城区信息
                aMapLocation.getStreet();//街道信息
                aMapLocation.getStreetNum();//街道门牌号信息
                aMapLocation.getCityCode();//城市编码
                aMapLocation.getAdCode();//地区编码

                if (isFirstLoc) {
                    isFirstLoc = false;
                    mLocationClient.stopLocation();//停止定位
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(
                            aMapLocation.getLatitude(), aMapLocation.getLongitude())));
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
                    MarkerOptions markerOption = new MarkerOptions();
                    markerOption.position(new LatLng(aMapLocation.getLatitude(),
                            aMapLocation.getLongitude()));
                    markerOption.title(aMapLocation.getCity());
                    markerOption.draggable(true);
                    aMap.addMarker(markerOption);
                    loadingDialog.dismiss();
                    addressView.setText(aMapLocation.getCity() + aMapLocation.getDistrict() +
                            aMapLocation.getStreet() + aMapLocation.getStreetNum());
                }
            } else {
                loadingDialog.dismiss();
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
                Toast.makeText(mContext, "定位失败", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }
    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }


    /** 检查定位权限 */
    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkPermission = ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION);
            if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
                Log.d(TAG, "弹出提示");
                return;
            } else {
                location();
            }
        } else {
            Log.d(TAG, "获取到权限");
            location();
        }
    }
}
